interface WebViewJavascriptBridge {
  init: (callback: () => void) => void;
  registerHandler: (handlerName: string, handler: (data: any, callback: (response: any) => void) => void) => void;
  callHandler: (handlerName: string, data?: any, callback?: (response: any) => void) => void;
}

declare global {
  interface Window {
    WebViewJavascriptBridge?: WebViewJavascriptBridge;
    WVJBCallbacks?: Array<(bridge: WebViewJavascriptBridge) => void>;
  }
}

export function setupWebViewJavascriptBridge(callback: (bridge: WebViewJavascriptBridge) => void) {
  if (window.WebViewJavascriptBridge) {
    callback(window.WebViewJavascriptBridge);
  } else {
    if (window.WVJBCallbacks) {
      window.WVJBCallbacks.push(callback);
    } else {
      window.WVJBCallbacks = [callback];
    }
  }
}

export function registerHandler(name: string, handler: (data: any, callback: (response: any) => void) => void) {
  setupWebViewJavascriptBridge((bridge) => {
    bridge.registerHandler(name, handler);
  });
}

export function callHandler(name: string, data?: any): Promise<any> {
  return new Promise((resolve) => {
    setupWebViewJavascriptBridge((bridge) => {
      bridge.callHandler(name, data, (response) => {
        resolve(response);
      });
    });
  });
}